<template>
  <!-- node-key属性很重要,指赋值给node的数据的某个属性, 该属性具有唯一性,往往是json对象的id(数据库主键)-->
  <el-tree
    ref="tree2"
    :data="treeData"
    node-key="permissionCode"
    :props="defaultProps"
    class="filter-tree"
    default-expand-all
    :check-strictly="true"
    :show-checkbox="showCheckbox"
  />
</template>

<script>
import { getToken } from '@/utils/auth'
import * as apiRole from '@/api/role'
export default {
  name: 'MenuTree',
  props: ['showCheckbox'],
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: (data, node)=>{
          let labelNew = data.label
          if (data.type === 'button') {
            labelNew = labelNew + '(按钮)'
          }
          return labelNew
        }
      },
      roleId: undefined,
      appName: undefined,
      canAssignPermission: false  //该角色是否可以为某个app 授权
    }
  },
  created() {

  },
  methods: {
    // 获取app的路由树
    // boolFetchRolePermission: 是否同时获取role对应的权限列表
    async getAppRouter(appName, boolFetchRolePermission) {
      this.appName = appName
      const { content } = await apiRole.getRouterByAppName(appName)
      this.treeData = content
      if (content && content.length==0) {
        this.$message('该项目没有发现路由, 请先在app端进行路由注册')
        this.canAssignPermission = false
      } else {
        this.canAssignPermission = true
        if (boolFetchRolePermission) {
          // 首先获取role的权限列表
          const { content } = await apiRole.getPermissionListByRole(this.roleId, appName)
          this.$refs.tree2.setCheckedKeys(content)
        }
      }
    },
    async init(roleId) {
      this.roleId = roleId //赋值给 类属性(java的解释,哈哈)
    },
    async confirmAssignPermission() {//确认修改角色的权限列表,很重要!!!
      if (!this.canAssignPermission) { //app没有路由,则直接跳过
        return
      }
      const checkedNodeList = this.$refs.tree2.getCheckedNodes(false, true) // 包含半选节点
      let permissionCodesStr = ''
      if (checkedNodeList.length == 0) {
      } else {// 类型为dir的节点需要 过滤掉
        const checkedNodeListAfter = checkedNodeList.filter((node)=>{
          return true //return node.type !== 'dir'
        })
        let permissionCodeArrayList = []
        checkedNodeListAfter.forEach((item)=>{
          permissionCodeArrayList.push(item.permissionCode)
        })
        permissionCodesStr = permissionCodeArrayList.join(',')
      }
      let jsonParams = {
        roleId: this.roleId,
        appName: this.appName,
        permissionCodes: permissionCodesStr
      }
      const { content } = await apiRole.confirmAssignPermission(jsonParams)
      this.$message(content)
    }
  }
}
</script>

<style>
  .el-tree-node__label {
    font-size: 18px;
    color: #999999;
    line-height: 25px;
  }

</style>
